//棋盘初始化
function drawChessBoard(board) {
    var rows = RULE_BOARD_ROWS;
    var cols = RULE_BOARD_COLS;
    var cellSize = RULE_CELL_SIZE;
    //1.棋盘
    board.innerHTML = '';
    board.style.width = cols * cellSize + 'px';
    board.style.height = rows * cellSize + 'px';
    board.style.border = '2px solid #8B4513';
    board.style.position = 'relative';
    board.style.backgroundColor = '#F5DEB3';
    board.style.zIndex = '1';
    //2.网格点
    document.querySelectorAll('.grid-point').forEach(point => point.remove());
    for (let y = 0; y < rows; y++) {
        for (let x = 0; x < cols; x++) {
            var point = document.createElement('div');
            point.className = 'grid-point';
            // 计算点的位置（位于格子中心）
            point.style.left = (x * cellSize + cellSize / 2) + 'px';
            point.style.top = (y * cellSize + cellSize / 2) + 'px';
            // 设置点的样式
            point.style.width = '6px';
            point.style.height = '6px';
            point.style.borderRadius = '50%';
            point.style.backgroundColor = '#8B4513'; // 棕色调与棋盘搭配
            point.style.position = 'absolute';
            point.style.transform = 'translate(-50%, -50%)'; // 中心点定位
            point.style.zIndex = '2'; // 确保点在棋盘之上，棋子之下
            point.style.pointerEvents = 'none'; // 不影响棋子交互
            board.appendChild(point);
        }
    }
    //3.河界
    var [redRiver, blackRiver] = [
        Math.min(Math.max(RULE_RED_RIVER) || 4, rows - 1),
        Math.min(Math.max(RULE_BLACK_RIVER) || 5, rows - 1)
    ]
    var redLineY = Math.max(0, Math.min((rows - redRiver - 1) * cellSize, board.offsetHeight - 2));
    var blackLineY = Math.max(0, Math.min((rows - blackRiver - 1) * cellSize, board.offsetHeight - 2)) + cellSize;
    // 移除旧的河界
    document.querySelectorAll('#red-river-line, #black-river-line, #red-river-line + div, #black-river-line + div').forEach(el => el.remove());
    // 绘制新的河界
    var redLine = document.createElement('div');
    redLine.id = 'red-river-line';
    redLine.style.position = 'absolute';
    redLine.style.top = redLineY + 'px';
    redLine.style.left = '0';
    redLine.style.width = '100%';
    redLine.style.height = '2px';
    redLine.style.backgroundColor = '#FF0000';
    redLine.style.borderTop = '1px dashed #FFAAAA';
    redLine.style.borderBottom = '1px dashed #FFAAAA';
    redLine.style.pointerEvents = 'none';
    redLine.style.zIndex = '2';
    var redText = document.createElement('div');
    redText.textContent = '河 界';
    redText.style.position = 'absolute';
    redText.style.top = (redLineY + cellSize/4 -16 + 5) + 'px';
    redText.style.left = '50%';
    redText.style.transform = 'translateX(-50%)';
    redText.style.color = '#C00';
    redText.style.fontSize = '12px';
    redText.style.fontWeight = 'bold';
    redText.style.pointerEvents = 'none';
    redText.style.zIndex = '2';
    var blackLine = document.createElement('div');
    blackLine.id = 'black-river-line';
    blackLine.style.position = 'absolute';
    blackLine.style.top = blackLineY + 'px';
    blackLine.style.left = '0';
    blackLine.style.width = '100%';
    blackLine.style.height = '2px';
    blackLine.style.backgroundColor = '#000000';
    blackLine.style.borderTop = '1px dashed #AAAAAA';
    blackLine.style.borderBottom = '1px dashed #AAAAAA';
    blackLine.style.pointerEvents = 'none';
    blackLine.style.zIndex = '2';
    var blackText = document.createElement('div');
    blackText.textContent = '河 界';
    blackText.style.position = 'absolute';
    blackText.style.top = (blackLineY - cellSize/4 - 5) + 'px';
    blackText.style.left = '50%';
    blackText.style.transform = 'translateX(-50%)';
    blackText.style.color = '#333';
    blackText.style.fontSize = '12px';
    blackText.style.fontWeight = 'bold';
    blackLine.style.alignContent = 'center';
    blackText.style.pointerEvents = 'none';
    blackText.style.zIndex = '2';

    board.appendChild(redLine);
    board.appendChild(redText);
    board.appendChild(blackLine);
    board.appendChild(blackText);
}
//棋子初始化
function drawChessLayout(board) {
    var rows = RULE_BOARD_ROWS;
    var cols = RULE_BOARD_COLS;
    var cellSize = RULE_CELL_SIZE;
    var layout = LAYOUT_CONFIG[RULE_LAYOUT_CONFIG];
    var redPalace = RULE_RED_PALACE;
    var blackPalace = RULE_BLACK_PALACE;
    //获取将帅坐标
    let unvalidOffset = -99999;
    let redBossPosition = null;
    let blackBossPosition = null;
    for (var i = 0; i < layout.length; i++) {
        let pieceData = layout[i];
        if (pieceData.type === '帅') {
            redBossPosition = {
                "x":pieceData.x,
                "y":pieceData.y
            };
            continue;
        }
        if (pieceData.type === '将') {
            blackBossPosition = {
                "x":pieceData.x,
                "y":pieceData.y
            };
            continue;
        }
    }
    if (redBossPosition == null) {
        redBossPosition = [unvalidOffset,unvalidOffset];
    }
    if (redBossPosition == null) {
        redBossPosition = [unvalidOffset,unvalidOffset];
    }
    //计算九宫格范围
    let redPalaceZone = [];
    let red_x_min = parseInt(redBossPosition.x) - parseInt(redPalace.left);
    let red_x_max = parseInt(redBossPosition.x) + parseInt(redPalace.right);
    let red_y_min = parseInt(redBossPosition.y) - parseInt(redPalace.bottom);
    let red_y_max = parseInt(redBossPosition.y) + parseInt(redPalace.top);
    for (var x = red_x_min; x <= red_x_max; x++) {
        for (var y = red_y_min; y <= red_y_max; y++) {
            let palacePosition = [x,y];
            redPalaceZone.push(palacePosition);
        }
    }
    DATA_RED_PALACE = redPalaceZone;
    let blackPalaceZone = [];
    let black_x_min = parseInt(blackBossPosition.x) - parseInt(blackPalace.left);
    let black_x_max = parseInt(blackBossPosition.x) + parseInt(blackPalace.right);
    let black_y_min = parseInt(blackBossPosition.y) - parseInt(blackPalace.bottom);
    let black_y_max = parseInt(blackBossPosition.y) + parseInt(blackPalace.top);
    for (var x = black_x_min; x <= black_x_max; x++) {
        for (var y = black_y_min; y <= black_y_max; y++) {
            let palacePosition = [x,y];
            blackPalaceZone.push(palacePosition);
        }
    }
    DATA_BLACK_PALACE = blackPalaceZone;
    //移除旧的九宫格
    document.querySelectorAll('.red-palace-line, .black-palace-line').forEach(el => el.remove());
    //绘制新的九宫格
    drawPalaceZone(board,cols,rows,cellSize,red_x_min,red_x_max,red_y_min,red_y_max,"red");
    drawPalaceZone(board,cols,rows,cellSize,black_x_min,black_x_max,black_y_min,black_y_max,"black");
    //摆放所有棋子
    for (var i = 0; i < layout.length; i++) {
        let pieceData = layout[i];
        //判断棋子类型的合法性
        let pieceConfig = CONFIG_CHESS[pieceData.type];
        if (pieceConfig == null) {
            continue;
        }
        //判断棋子是否在九宫格外
        let outOfPalace = pieceConfig.outOfPalace || true;
        if (!outOfPalace) {
            let chessPosition = [pieceData.x,pieceData.y];
            if (pieceData.clan === 'red' && !Arrays_2dContain1d(redPalaceZone,chessPosition)) {
                continue;
            }
            if (pieceData.clan === 'black' && !Arrays_2dContain1d(blackPalaceZone,chessPosition)) {
                continue;
            }
        };
        //判断是否在棋盘上
        if (pieceData.x >= cols) {
            continue;
        }
        if (pieceData.y >= rows) {
            continue;
        }
        //创建棋子
        let piece = document.createElement('div');
        piece.className = 'piece';
        piece.textContent = pieceData.type;
        piece.dataset.type = pieceData.type;
        piece.dataset.clan = pieceData.clan;
        piece.dataset.x = pieceData.x;
        piece.dataset.y = pieceData.y;
        piece.id = `${pieceData.clan}_${pieceData.type}_${pieceData.x}_${pieceData.y}`;
        piece.style.left = (pieceData.x * cellSize + (cellSize - 60) / 2) + 'px';
        piece.style.top = ((board.offsetHeight - cellSize * (pieceData.y + 1)) + (cellSize - 60) / 2 - 4) + 'px';
        piece.style.color = pieceData.clan === 'red' ? '#C00' : '#000';
        let nameLength = pieceData.type.length;
        if (nameLength === 1) {
            piece.style.fontSize = '36px';
        }
        else if (nameLength === 2) {
            piece.style.fontSize = '24px';
        }
        else if (nameLength === 3) {
            piece.style.fontSize = '18px';
        }
        else {
            piece.style.fontSize = '12px';
        }
        piece.style.fontWeight = 'bold';
        piece.style.textShadow = '1px 1px 1px rgba(0,0,0,0.2)';
        piece.style.backgroundColor = 'antiquewhite';
        piece.style.zIndex = '3';
        board.appendChild(piece);
        DATA_CHESS[piece.id] = {
            "id":piece.id,
            "piece":piece,
            "config":pieceConfig,
            "grid":pieceData.x+","+pieceData.y,
            "alive":true,
        };
        DATA_CHESS_GRID[pieceData.x+","+pieceData.y] = DATA_CHESS[piece.id];
    };
}
function drawPalaceZone(board,cols,rows,cellSize,xLeft,xRight,yBottom,yTop,clan){
    const rect = board.getBoundingClientRect();
    const originX = (window.pageXOffset || document.documentElement.scrollLeft);
    const originY = (window.pageYOffset || document.documentElement.scrollTop) + rows*cellSize;
    const boardRight = originX+cols*cellSize;
    const boardLeft = originX;
    const boardTop = originY-rows*cellSize;
    const boardBottom = originY;
    var color = clan === 'red' ? '#C00' : '#000';
    // 转换为像素坐标
    const squareLeft = originX + xLeft * cellSize;
    const squareRight = originX + xRight * cellSize;
    const squareTop = originY - yTop * cellSize - cellSize;
    const squareBottom = originY - yBottom * cellSize;
    // 确保不超出底板边界
    const fixedLeft = Math.max(squareLeft, boardLeft);
    const fixedRight = Math.min(squareRight+cellSize, boardRight);
    const fixedTop = Math.max(squareTop, boardTop);
    const fixedBottom = Math.min(squareBottom, boardBottom);
    // 创建线条的辅助函数
    function createLine() {
        const line = document.createElement('div');
        line.className = clan + '-palace-line';  // 修正class为className
        line.style.position = 'absolute';
        line.style.backgroundColor = color;
        line.style.border = '1px dotted ' + color;
        line.style.pointerEvents = 'none';
        line.style.zIndex = '2';
        board.appendChild(line);
        return line;
    }
    // 上边界（顶边）
    const topLine = createLine();
    topLine.style.left = fixedLeft + 'px';
    topLine.style.top = fixedTop + 'px';
    topLine.style.width = (fixedRight - fixedLeft) + 'px';
    topLine.style.height = '1px';
    // 下边界（底边）
    const bottomLine = createLine();
    bottomLine.style.left = fixedLeft + 'px';
    bottomLine.style.top = fixedBottom + 'px';
    bottomLine.style.width = (fixedRight - fixedLeft) + 'px';
    bottomLine.style.height = '1px';
    // 左边界（左边）
    const leftLine = createLine();
    leftLine.style.left = fixedLeft + 'px';
    leftLine.style.top = fixedTop + 'px';
    leftLine.style.width = '1px';
    leftLine.style.height = (fixedBottom - fixedTop) + 'px';
    // 右边界（右边）
    const rightLine = createLine();
    rightLine.style.left = fixedRight + 'px';
    rightLine.style.top = fixedTop + 'px';
    rightLine.style.width = '1px';
    rightLine.style.height = (fixedBottom - fixedTop) + 'px';
}
function Arrays_2dContain1d(twoDArray, oneDArray) {
    return twoDArray.some(item =>
        item.length === oneDArray.length &&
        item.every((value, index) => value === oneDArray[index])
    );
}